<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="分配人员" prop="assignedPersonId" v-if="!isAdmin">
        <el-select
          v-model="selectedValue"
          placeholder="请选择分配人员"
          clearable
          class="!w-240px"
          @change="handlePersonChange"
        >
          <el-option
            v-for="item in fenpei"
            :key="item.id"
            :label="item.nickname"
            :value="`${item.id}|${item.nickname}`"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="来源渠道" prop="source" v-if="!isAdmin">
        <el-select
          v-model="formData.source"
          placeholder="请输入来源渠道"
          clearable
        >
          <el-option label="电话" value="1" />
          <el-option label="邮件" value="2" />
          <el-option label="系统上报" value="3" />
          <el-option label="APP" value="4" />
          <el-option label="微信" value="5" />
        </el-select>
      </el-form-item>
      <el-form-item label="机器人类型" prop="robotType" v-if="!isAdmin">
        <el-select
          v-model="formData.robotType"
          placeholder="请选择机器人类型"
          clearable
        >
          <el-option label="智能盘点机器人" value="1" />
          <el-option label="智能还书系统" value="2" />
          <el-option label="智能导览机器人" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="机器人编号" prop="robotCode">
        <el-input v-model="formData.robotCode" placeholder="请输入机器人编号" />
      </el-form-item>
      <el-form-item label="机器人名称" prop="robotName" v-if="!isAdmin">
        <el-input v-model="formData.robotName" placeholder="请输入机器人名称" />
      </el-form-item>
      <el-form-item label="当前状态" prop="status" v-if="!isAdmin">
        <el-select
          v-model="formData.status"
          placeholder="请选择当前状态"
          clearable
        >
          <el-option label="待分配" value="1" />
          <el-option label="已分配" value="2" />
          <el-option label="处理中" value="3" />
          <el-option label="待确认" value="4" />
          <el-option label="已完成" value="5" />
          <el-option label="已关闭" value="6" />
          <el-option label="已取消" value="7" />
        </el-select>
      </el-form-item>
      <el-form-item label="优先级" prop="priority" v-if="!isAdmin">
        <el-select
          v-model="formData.priority"
          placeholder="请选择优先级"
          clearable
        >
          <el-option label="P0" value="P0" />
          <el-option label="P1" value="P1" />
          <el-option label="P2" value="P2" />
          <el-option label="P3" value="P3" />
          <el-option label="P4" value="P4" />
        </el-select>
      </el-form-item>
      <el-form-item label="问题分类" prop="category" v-if="!isAdmin">
        <el-select
          v-model="formData.category"
          placeholder="请选择问题分类"
          clearable
        >
          <el-option label="一级分类" value="一级分类" />
          <el-option label="二级分类" value="一级分类" />
        </el-select>
      </el-form-item>

      <el-form-item label="问题描述" prop="description">
        <Editor
          v-model="formData.description"
          height="150px"
          :readonly="isAdminyun_wei"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <Editor v-model="formData.remark" height="150px" />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName" v-if="!isAdmin">
        <el-input
          v-model="formData.customerName"
          placeholder="请输入客户名称"
        />
      </el-form-item>
      <el-form-item label="联系人" prop="contactPerson" v-if="!isAdmin">
        <el-input v-model="formData.contactPerson" placeholder="请输入联系人" />
      </el-form-item>
      <el-form-item label="联系方式" prop="contactInfo">
        <el-input v-model="formData.contactInfo" placeholder="请输入联系方式" />
      </el-form-item>
      <el-form-item label="产品型号" prop="productModel" v-if="!isAdmin">
        <el-input
          v-model="formData.productModel"
          placeholder="请输入产品型号"
        />
      </el-form-item>
      <el-form-item label="购买日期" prop="purchaseDate" v-if="!isAdmin">
        <el-date-picker
          v-model="formData.purchaseDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="选择购买日期"
        />
      </el-form-item>
      <el-form-item label="保修状态" prop="warrantyStatus" v-if="!isAdmin">
        <el-select
          v-model="formData.warrantyStatus"
          placeholder="请选择保修状态"
          clearable
        >
          <el-option label="在保" value="1" />
          <el-option label="过保" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="保修截止日期" prop="warrantyExpiry" v-if="!isAdmin">
        <el-date-picker
          v-model="formData.warrantyExpiry"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="选择保修截止日期"
        />
      </el-form-item>
      <el-form-item label="购买凭证" prop="purchaseProof">
        <UploadImg v-model="formData.purchaseProof" />
      </el-form-item>
      <el-form-item label="延保信息" prop="extendedWarranty" v-if="!isAdmin">
        <el-input
          v-model="formData.extendedWarranty"
          placeholder="请输入延保信息"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading"
        >确 定</el-button
      >
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import {
  RobotAftersalesApi,
  RobotAftersalesVO,
} from "@/api/health/robotaftersales";
import { useUserStoreWithOut } from "@/store/modules/user";
const userStore = useUserStoreWithOut(); // 用户信息缓存
const isAdmin = computed(() => userStore.roles.includes("ke_hu"));
const isAdminyun_wei = computed(() => userStore.roles.includes("yun_wei"));
/** 售后工单 表单 */
defineOptions({ name: "RobotAftersalesForm" });

const { t } = useI18n(); // 国际化
const message = useMessage(); // 消息弹窗

const dialogVisible = ref(false); // 弹窗的是否展示
const dialogTitle = ref(""); // 弹窗的标题
const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref(""); // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  libraryId: undefined,
  assignedPersonId: undefined,
  assignedPerson: undefined,
  source: undefined,
  robotType: undefined,
  robotId: undefined,
  robotCode: undefined,
  robotName: undefined,
  status: undefined,
  priority: undefined,
  category: undefined,
  description: undefined,
  customerId: undefined,
  customerName: undefined,
  contactPerson: undefined,
  contactInfo: undefined,
  productModel: undefined,
  purchaseDate: undefined,
  warrantyStatus: undefined,
  warrantyExpiry: undefined,
  purchaseProof: undefined,
  extendedWarranty: undefined,
  remark: undefined,
});
const formRules = reactive({
  robotCode: [
    { required: true, message: "机器人编号不能为空", trigger: "blur" },
  ],
  assignedPersonId: [
    { required: true, message: "请选择分配人员", trigger: "chang" },
  ],
  description: [
    { required: true, message: "问题描述不能为空", trigger: "blur" },
  ],
});
const formRef = ref(); // 表单 Ref
const fenpei = ref([] as any);
// 选择框的临时绑定值（组合值）
const selectedValue = ref("");

// 处理选择变化
const handlePersonChange = (combinedValue) => {
  if (combinedValue) {
    const [id, nickname] = combinedValue.split("|");
    formData.value.assignedPersonId = id;
    formData.value.assignedPerson = nickname;
  } else {
    // 清空时重置
    formData.value.assignedPersonId = undefined;
    formData.value.assignedPerson = undefined;
  }
};

// 如果是编辑模式，初始化组合值
if (formData.value.assignedPersonId && formData.value.assignedPerson) {
  selectedValue.value = `${formData.value.assignedPersonId}|${formData.value.assignedPerson}`;
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true;
  dialogTitle.value = t("action." + type);
  formType.value = type;
  fenpei.value = await RobotAftersalesApi.getRobotAfterslist();
  resetForm();
  // 修改时，设置数据
  if (id) {
    formLoading.value = true;
    try {
      formData.value = await RobotAftersalesApi.getRobotAftersales(id);

      if (formData.value.description === null) {
        formData.value.description = undefined; // 手动修正
        formData.value.remark = undefined; // 手动修正
      }
    } finally {
      formLoading.value = false;
    }
  }
};
defineExpose({ open }); // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(["success"]); // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate();
  // 提交请求
  formLoading.value = true;
  try {
    const data = formData.value as unknown as RobotAftersalesVO;
    if (formType.value === "create") {
      await RobotAftersalesApi.createRobotAftersales(data);
      message.success(t("common.createSuccess"));
    } else {
      await RobotAftersalesApi.updateRobotAftersales(data);
      message.success(t("common.updateSuccess"));
    }
    dialogVisible.value = false;
    // 发送操作成功的事件
    emit("success");
  } finally {
    formLoading.value = false;
  }
};

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    libraryId: undefined,
    assignedPersonId: undefined,
    assignedPerson: undefined,
    source: undefined,
    robotType: undefined,
    robotId: undefined,
    robotCode: undefined,
    robotName: undefined,
    status: undefined,
    priority: undefined,
    category: undefined,
    description: undefined,
    customerId: undefined,
    customerName: undefined,
    contactPerson: undefined,
    contactInfo: undefined,
    productModel: undefined,
    purchaseDate: undefined,
    warrantyStatus: undefined,
    warrantyExpiry: undefined,
    purchaseProof: undefined,
    extendedWarranty: undefined,
  };
  formRef.value?.resetFields();
};
</script>
